//
//  TodayViewController.swift
//  CblToday
//
//  Created by DKHS on 2018/1/16.
//  Copyright © 2018年 CBL. All rights reserved.
//

import UIKit
import NotificationCenter

class TodayViewController: UIViewController, NCWidgetProviding {
    
    /// <#注释#>
    fileprivate lazy var titleLabel: UILabel = {
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20.0))
        titleLabel.backgroundColor = UIColor.blue
        return titleLabel
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(titleLabel)
        if #available(iOSApplicationExtension 10.0, *) {
            extensionContext?.widgetLargestAvailableDisplayMode = .expanded
        } else {
            // Fallback on earlier versions
        }
        let shareUserDefaults = UserDefaults(suiteName: "group.WebViewJavaScript.CblToady")
        if let titleString = shareUserDefaults?.object(forKey: "CblTodayKey") as? String {
            titleLabel.text = titleString
        }
        
        if var containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.WebViewJavaScript.CblToady") {
            containerURL.appendPathComponent("Library/Caches/test")
            if let titleString = try? String(contentsOf: containerURL, encoding: String.Encoding.utf8) {
                titleLabel.text = (titleLabel.text ?? "") + titleString
            }
        }
        
    }
    
    @IBAction func didClickOpenButton(_ sender: UIButton) {
        extensionContext?.open(URL(string: "WebViewJavaScript://")!, completionHandler: { (isSuccess) in
            sender.setTitle(isSuccess ? "打开成功" : "打开失败", for: .normal)
            
            
            
        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
        // Perform any setup necessary in order to update the view.
        
        // If an error is encountered, use NCUpdateResult.Failed
        // If there's no update required, use NCUpdateResult.NoData
        // If there's an update, use NCUpdateResult.NewData
        
        completionHandler(NCUpdateResult.newData)
    }
    
    func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
        return UIEdgeInsetsMake(10, 30, 50, 60)
    }
    
    @available(iOSApplicationExtension 10.0, *)
    func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
        if activeDisplayMode == .compact {
            preferredContentSize = maxSize
        } else {
            preferredContentSize = CGSize(width: 0.0, height: 400.0)
        }
    }
    
}

